import './import';

import Header from "../components/Header";
import NewsFrame from "../components/iFrame";
import Follow from "../components/Follow"
import { getUrlQueryValue } from "../libs/utils";


;((doc) => {

    const oApp = doc.querySelector('#app');
    // 从本地存储中取出点击的新闻数据
    const currentNews = JSON.parse(localStorage.getItem('currentNews'));
    const followedList = JSON.parse(localStorage.getItem('followedList') || '[]');

    const init = () => {
        render();
        bindEvent();
    }
    // 渲染页面
    function render () {
        // 渲染头部
        const headerTpl = Header.tpl({
            url: getUrlQueryValue('path'),
            title: '新闻详情',
            showLeftIcon: true,
            showRightIcon: false
        })
        // 渲染详情页的iFrame详情
        const newsFrameTpl = NewsFrame.tpl(currentNews.url);
        const followTpl = createFollowTpl();
        // 组合到页面中
        oApp.innerHTML += (headerTpl + newsFrameTpl + followTpl);
    }

    function createFollowTpl () {
        const isExist = followedList.find(item => item.uniquekey == currentNews.uniquekey);
        return isExist ? Follow.follow() : Follow.unFollow();
    }

    function bindEvent () {
        Follow.bindEvent(doFollow);
    }

    function doFollow (status) {
        let followedList = JSON.parse(localStorage.getItem('followedList') || '[]');

        if (status) {
            followedList.push(currentNews);
        } else {
            followedList = followedList.filter(item => item.uniquekey !== currentNews.uniquekey);
        }

        localStorage.setItem('followedList', JSON.stringify(followedList));
    }

    init();
})(document)